import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { supabase, handleSupabaseError, TABLES } from '@/lib/supabase'

export const useCourtStore = defineStore('court', () => {
  // 状态
  const courts = ref([])
  const bookings = ref([])
  const loading = ref(false)
  
  // 计算属性
  const availableCourts = computed(() => courts.value.filter(court => court.status === 'available'))
  
  // 动作
  const loadCourts = async () => {
    loading.value = true
    try {
      const { data, error } = await supabase
        .from(TABLES.COURTS)
        .select(`
          *,
          time_slots (*)
        `)
        .order('name')
      
      if (error) {
        console.error('加载球场失败:', error)
        return
      }
      
      courts.value = data || []
    } catch (error) {
      console.error('加载球场失败:', error)
    } finally {
      loading.value = false
    }
  }
  
  const loadBookings = async () => {
    if (!courts.value.length) {
      await loadCourts()
    }
    
    loading.value = true
    try {
      const { data, error } = await supabase
        .from(TABLES.BOOKINGS)
        .select(`
          *,
          courts!inner(name),
          time_slots!inner(time_range, price)
        `)
        .eq('status', 'confirmed')
        .order('booking_date', { ascending: true })
        .order('created_at', { ascending: false })
      
      if (error) {
        console.error('加载预约失败:', error)
        return
      }
      
      bookings.value = data || []
    } catch (error) {
      console.error('加载预约失败:', error)
    } finally {
      loading.value = false
    }
  }
  
  const getUserBookings = async () => {
    const { data: { user } } = await supabase.auth.getUser()
    if (!user) return []
    
    loading.value = true
    try {
      const { data, error } = await supabase
        .from(TABLES.BOOKINGS)
        .select(`
          *,
          courts!inner(name),
          time_slots!inner(time_range, price)
        `)
        .eq('user_id', user.id)
        .order('booking_date', { ascending: true })
        .order('created_at', { ascending: false })
      
      if (error) {
        console.error('获取用户预约失败:', error)
        return []
      }
      
      return data || []
    } catch (error) {
      console.error('获取用户预约失败:', error)
      return []
    } finally {
      loading.value = false
    }
  }
  
  const bookCourt = async (courtId, timeSlotId, bookingDate) => {
    const { data: { user } } = await supabase.auth.getUser()
    if (!user) {
      return { success: false, message: '请先登录' }
    }
    
    loading.value = true
    try {
      // 检查是否已有相同预约
      const { data: existingBooking } = await supabase
        .from(TABLES.BOOKINGS)
        .select('id')
        .eq('user_id', user.id)
        .eq('court_id', courtId)
        .eq('time_slot_id', timeSlotId)
        .eq('booking_date', bookingDate)
        .eq('status', 'confirmed')
        .single()
      
      if (existingBooking) {
        return { success: false, message: '您已经预约了这个时间段' }
      }
      
      // 获取时间段信息
      const { data: timeSlot, error: timeSlotError } = await supabase
        .from(TABLES.TIME_SLOTS)
        .select('price')
        .eq('id', timeSlotId)
        .single()
      
      if (timeSlotError || !timeSlot) {
        return { success: false, message: '时间段信息不存在' }
      }
      
      // 创建预约
      const { data, error } = await supabase
        .from(TABLES.BOOKINGS)
        .insert([
          {
            user_id: user.id,
            court_id: courtId,
            time_slot_id: timeSlotId,
            booking_date: bookingDate,
            price: timeSlot.price,
            status: 'confirmed'
          }
        ])
        .select(`
          *,
          courts!inner(name),
          time_slots!inner(time_range, price)
        `)
        .single()
      
      if (error) {
        return { success: false, message: handleSupabaseError(error, '预约失败') }
      }
      
      // 更新本地预约列表
      bookings.value.unshift(data)
      
      return { success: true, message: '预约成功', data }
    } catch (error) {
      return { success: false, message: handleSupabaseError(error, '预约失败') }
    } finally {
      loading.value = false
    }
  }
  
  const cancelBooking = async (bookingId) => {
    const { data: { user } } = await supabase.auth.getUser()
    if (!user) {
      return { success: false, message: '请先登录' }
    }
    
    loading.value = true
    try {
      const { error } = await supabase
        .from(TABLES.BOOKINGS)
        .update({ 
          status: 'cancelled',
          updated_at: new Date().toISOString()
        })
        .eq('id', bookingId)
        .eq('user_id', user.id)
      
      if (error) {
        return { success: false, message: handleSupabaseError(error, '取消预约失败') }
      }
      
      // 从本地列表中移除
      const index = bookings.value.findIndex(b => b.id === bookingId)
      if (index > -1) {
        bookings.value.splice(index, 1)
      }
      
      return { success: true, message: '取消预约成功' }
    } catch (error) {
      return { success: false, message: handleSupabaseError(error, '取消预约失败') }
    } finally {
      loading.value = false
    }
  }
  
  const getAvailableTimeSlots = async (courtId, bookingDate) => {
    try {
      // 获取该球场所有时间段
      const { data: allTimeSlots, error: timeSlotsError } = await supabase
        .from(TABLES.TIME_SLOTS)
        .select('*')
        .eq('court_id', courtId)
        .order('time_range')
      
      if (timeSlotsError) {
        console.error('获取时间段失败:', timeSlotsError)
        return []
      }
      
      // 获取该日期已预约的时间段
      const { data: bookedSlots, error: bookedError } = await supabase
        .from(TABLES.BOOKINGS)
        .select('time_slot_id')
        .eq('court_id', courtId)
        .eq('booking_date', bookingDate)
        .eq('status', 'confirmed')
      
      if (bookedError) {
        console.error('获取已预约时间段失败:', bookedError)
        return allTimeSlots || []
      }
      
      const bookedSlotIds = new Set(bookedSlots?.map(slot => slot.time_slot_id) || [])
      
      // 过滤出可用时间段
      return allTimeSlots?.map(slot => ({
        ...slot,
        available: !bookedSlotIds.has(slot.id)
      })) || []
    } catch (error) {
      console.error('获取可用时间段失败:', error)
      return []
    }
  }
  
  // 实时订阅预约变化
  const subscribeToBookings = () => {
    supabase
      .channel('bookings_changes')
      .on('postgres_changes', 
        { 
          event: '*', 
          schema: 'public', 
          table: TABLES.BOOKINGS 
        },
        (payload) => {
          console.log('预约变化:', payload)
          // 重新加载预约数据
          loadBookings()
        }
      )
      .subscribe()
  }
  
  return {
    courts,
    bookings,
    loading,
    availableCourts,
    loadCourts,
    loadBookings,
    getUserBookings,
    bookCourt,
    cancelBooking,
    getAvailableTimeSlots,
    subscribeToBookings
  }
})
